package net.thxjj.adminServer.controller;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.thxjj.adminServer.controller.base.BaseController;
import net.thxjj.adminServer.entity.ResponseModel;
import net.thxjj.adminServer.entity.ResultEnum;
import net.thxjj.adminServer.service.IExcelDeviceService;
import net.thxjj.adminServer.service.IUserApiService;
import net.thxjj.adminServer.util.excel.PoiUtil;
import net.thxjj.sitermodel.User;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import net.thxjj.adminServer.util.ImgUtil;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

	private Logger log = Logger.getLogger(this.getClass());
	
	private final ResourceLoader resourceLoader;  
	
	@Value("${upload.root.folder}")
	public String root_fold;
	
	@Value("${file.folder}")
	public String file_fold;
	
	@Value("${user.folder}")
	public String user_folder;

    @Autowired
    private IUserApiService iUserApiService;

    @Autowired
    private IExcelDeviceService iExcelDeviceService;
	
    @Autowired 
    public UploadController(ResourceLoader resourceLoader) {  
        this.resourceLoader = resourceLoader;  
    }

	@RequestMapping(value = "/img" ,method = RequestMethod.POST)
	@ResponseBody
	public Object imgUpload(@RequestParam(value = "file") MultipartFile file){

		if (file.isEmpty()) {
            return ResponseModel.getModel(ResultEnum.FILE_IS_EMPTY_ERROR,null);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        log.info("上传的文件名为：" + fileName);
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        log.info("上传的后缀名为：" + suffixName);
        String freName = fileName.substring(0,fileName.lastIndexOf("."));

        String LastFileName = freName+System.currentTimeMillis()+suffixName;
        // 文件上传后的路径
        String filePath = root_fold+user_folder;
        System.out.println("upload_img_folder="+root_fold);
        System.out.println("upload_folder_root="+user_folder);
        System.out.println("filePath="+filePath);
        ImgUtil.createFileFold(filePath);
        File dest = new File(filePath + LastFileName);
        try {
            file.transferTo(dest);
            System.out.println("upload  success");
        }catch (IOException e) {
            e.printStackTrace();
            return ResponseModel.getModel(ResultEnum.FILE_UPLOAD_ERROR,null);
        }
        return ResponseModel.getModel(ResultEnum.SUCCESS, "/upload/show"+user_folder+LastFileName);
	}

    @RequestMapping(value = "/excel" ,method = RequestMethod.POST)
    @ResponseBody
    public Object excelUpload(@RequestParam(value = "file") MultipartFile file){

        String token = this.getRequest().getHeader("token");
        User userinfo = iUserApiService.getUserInfoByToken(token);

        return iExcelDeviceService.excelImport(file,userinfo);
    }

    /**
     * 显示上传的图片
     * @param folderName
     * @param filename
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/show/{folderName}/{filename:.+}")
    @ResponseBody
    public ResponseEntity<?> getImg(@PathVariable("folderName") String folderName,@PathVariable("filename") String filename) {
    	try {
    		return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(root_fold+"/"+folderName, filename).toString()));
    	} catch (Exception e) {
    		return ResponseEntity.notFound().build();
    	}
    }

    /**
     * 获取设备导入模版
     * @return
     */
    @RequestMapping(value="/exportTemplate",method= RequestMethod.GET)
    @ResponseBody
    public void exportTemplate() throws Exception {
        final String[] headers = new String[]{"imei", "prod_key", "设备名称"};

        List<Map<Integer,Object>> list2 = new ArrayList<>();
        Map<Integer,Object> de = new HashMap<Integer,Object>();
        de.put(0,"864481059882032");
        de.put(1,"5002786");
        de.put(2,"test_smoke");

        Map<Integer,Object> de2 = new HashMap<Integer,Object>();
        de2.put(0,"861050045547885");
        de2.put(1,"10092853");
        de2.put(2,"my_smoke");

        list2.add(de);
        list2.add(de2);
        //将listMap填入真正的excel对应的workbook
        Workbook workbook = PoiUtil.fillExcelSheetData(list2, headers, "device_register_template.xls");
        //将excel实例以流的形式写回浏览器
        PoiUtil.downloadExcel(this.getResponse(), workbook, "device_register_template.xls");
    }


}
